"""
author : wlingforever
file name : db_upload
last modified time:2022.10.8

description:
    save image from database

"""
import os
from datetime import date
import pymysql

# from pymysql import MySQLError

'''
建立连接                                                                                                                                                                                                                      
'''
# host 主机 port 端口
# charset=字符集
pnw = 'localhost'
username = 'rdmanager'
ur_password = 'rdm2022.'
# username = 'rdquery'
# ur_password = 'rdquery2022'
# pnw = '100.65.255.40'

coon = pymysql.connect(host=pnw, port=3306,
                       user='rdmanager', password='rdm2022.',
                       database='rfo_detection', charset='utf8mb4')

print(coon)
try:
    # print(coon)
    # 获取游标对象
    with coon.cursor(cursor=pymysql.cursors.DictCursor) as cursor:
        # 通过对象向数据库发sql语句，获取执行结果
        sql_select = "select image_name,key_id,im_row, im_col,image_mat from tb_image_mat_data "
        cursor.execute(sql_select)
        # print(cursor.fetchone())
        # result is a dict
        images_md = []
        for row in iter(lambda: cursor.fetchone(), None):
            images_md.append(row)
        # row = cursor.fetchone()
        # while row:
        #     image.append(row)
        #     row = cursor.fetchone()
        # print(images_md)

        print("images find成功!")
    print("database operation complete")

except pymysql.MySQLError as err:
    print("find error")
    print(err)

finally:
    coon.close()


try:
    # get image matrix values
    for arrs_data in images_md:
        arr_data = arrs_data['image_mat']

        # print(arrs_data['image_name'])
        # get date to create folder if not exist
        date_path = date.today()
        if not os.path.exists(f'../runs/{date_path}'):
            os.makedirs(f'../runs/{date_path}')
            print("creat folder successfully")
        # write data to image and save
        with open(f'../runs/{date_path}/{arrs_data["image_name"]}', 'wb') as f:
            f.write(arr_data)
    print("image save successfully")


except Exception as err:
    print("image save error!")
    print(err)


